/* 
 * File:   FileCachedCleanTimer.cpp
 * Author: dell
 * 
 * Created on 2012年11月21日, 下午4:47
 */

#include "FileCachedCleanTimer.h"
#include "config/CacheConfig.h"
#include "config/ServerConfig.h"
#include <vector>
#include <dirent.h>
#include "FileCached.h"
#include "RapidMain.h"

using namespace std;

namespace Rapid{
    FileCachedCleanTimer::FileCachedCleanTimer(RapidConfigManager* rapidConfigManager):rapidConfigManager(rapidConfigManager) {
        init();
    }


    FileCachedCleanTimer::~FileCachedCleanTimer() {
        processMessage.close();
        LOG_DEBUG("fileCachedMap.size:%d", fileCachedMap.size());
        FileCachedMap::iterator it = fileCachedMap.begin();
        for(; it != fileCachedMap.end(); it++){
            delete it->second;
        }
    }
    
    void FileCachedCleanTimer::init(){

        vector<ServerConfig*>* serverConfigs = rapidConfigManager->getServerConfigs();
        LOG_DEBUG("serverConfigs->size():%d", serverConfigs->size());
        vector<ServerConfig*>::iterator scfgit = serverConfigs->begin();
        for(; scfgit != serverConfigs->end(); scfgit++){
            ServerConfig* serverConfig = *scfgit;
            if(serverConfig->cacheConfig.existCacheConfig){
                FileCached* fc = new FileCached(serverConfig);
                fileCachedMap.insert(FileCachedMap::value_type(serverConfig->port, fc));
                fc->syncCachedFiles(&serverConfig->cacheConfig);
                fc->makeSourceFileEvstats(serverConfig->cacheConfig.base.c_str());
            }
        }
        
        
        //打开进程消息队列
        processMessage.open(RapidMain::homeDir.c_str());
        
    }
    
    bool FileCachedCleanTimer::onTimerEvent(const TimerEvent* e){
        #define msgsize 1024
        char msg[msgsize] = {0};

                    
        ssize_t rsize = processMessage.receive(msg, msgsize);
        LOG_DEBUG("rsize:%d", rsize);
        if(rsize > 0){
            int* portpt = (int*)msg;
            long* filesizept = (long*)(msg+sizeof(int));
            char* shmfilename = msg+sizeof(int)+sizeof(long);
            LOG_DEBUG("rsize:%d", rsize);
            LOG_DEBUG("msg.port:%d", *portpt);
            LOG_DEBUG("msg.shmFilenamesize:%d", *filesizept);
            LOG_DEBUG("msg.shmFilename:%s", shmfilename);                
            FileCachedMap::iterator it = fileCachedMap.find(*portpt);
            if(it != fileCachedMap.end()){
                it->second->newSourceFileEvstat(shmfilename, *filesizept);
            }
            
        }
        return true;
    }
}

